# -*- coding: utf-8 -*-
# @时间：2023/11/4 14:38
# @作者：CJiaの可乐哥
# @文件名：cj_curd
# @软件：Pycharm2023
from django.shortcuts import get_object_or_404

from utils.cj_auth import authenticate
from utils.usual import get_user_info_from_token
from utils.cj_response import SuccessResponse, ErrorResponse


@authenticate
def delete(request, id, model):
    instance = get_object_or_404(model, id=id)
    instance.delete()
    return SuccessResponse(msg="删除成功")


@authenticate
def update(request, id, data, model):
    dict_data = data.dict()
    user = get_user_info_from_token(request)
    dict_data['modifier'] = user.name
    instance = get_object_or_404(model, id=id)
    for attr, value in dict_data.items():
        setattr(instance, attr, value)
    instance.save()
    return instance


@authenticate
def status(request, id, model):
    menu = model.objects.get(id=id)
    if menu.status:
        menu.status = False
        menu.save()
        return SuccessResponse(msg="禁用成功")
    else:
        menu.status = True
        menu.save()
        return SuccessResponse(msg="解除成功")


def retrieve(request, model, filters):
    if filters is not None:
        # 将filters空字符串转换为None
        for attr, value in filters.__dict__.items():
            if getattr(filters, attr) == '':
                setattr(filters, attr, None)
        query_set = model.objects.filter(**filters.dict(exclude_none=True))
    else:
        query_set = model.objects.all()
    return query_set
